package cn.signalpha.modules.social.service;

import cn.signalpha.common.cache.ConfigCache;
import cn.signalpha.common.cache.ConfigKeys;
import cn.signalpha.common.constant.MsgConstant;
import cn.signalpha.common.dto.ConfigDTO;
import cn.signalpha.common.utils.Assert;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.com.service.UserService;
import cn.signalpha.modules.social.dto.CommentDTO;
import cn.signalpha.modules.social.entity.Comment;
import cn.signalpha.modules.social.entity.Topic;
import cn.signalpha.modules.social.mapper.CommentMapper;
import cn.signalpha.modules.social.vo.CommentVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 服务类
 *
 * @author signalpha
 */
@Service
@AllArgsConstructor
public class CommentService extends ServiceImpl<CommentMapper, Comment> {

	private final UserService userService;
	private final TopicService topicService;
//	private final NoticeService noticeService;
	private final ApplicationEventPublisher eventPublisher;

	/**
	 * 一级评论分页
	 */
    public IPage<CommentVO> selectCommentPage(IPage<CommentVO> page, Map<String, Object> params) {
        return page.setRecords(baseMapper.selectCommentPage(page, params));
    }

	/**
	 * 二级评论分页
	 */
	public IPage<CommentVO> selectCommentReplyPage(IPage<CommentVO> page, Map<String, Object> params) {
		return page.setRecords(baseMapper.selectCommentReplyPage(page, params));
	}

	/**
	 * 自定义列表
	 */
	public List<CommentVO> selectCommentList(Map<String, Object> params) {
		return baseMapper.selectCommentPage(null, params);
	}

	/**
	 * 自定义Wrapper
	 */
	public QueryWrapper<Comment> selectCommentWrapper(Map<String, Object> params) {
		QueryWrapper<Comment> wrapper = Wrappers.query();
		wrapper.lambda().in(ObjectUtil.isNotEmpty(params.get("ids")), Comment::getId, Func.toLongList(String.valueOf(params.get("ids"))));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("fromUserId")), Comment::getFromUserId, params.get("fromUserId"));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("toUserId")), Comment::getToUserId, params.get("toUserId"));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("status")), Comment::getStatus, params.get("status"));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("isShow")), Comment::getIsShow, params.get("isShow"));
		wrapper.lambda().ge(ObjectUtil.isNotEmpty(params.get("createTimeBegin")), Comment::getCreateTime, params.get("createTimeBegin"));
		wrapper.lambda().le(ObjectUtil.isNotEmpty(params.get("createTimeEnd")), Comment::getCreateTime, params.get("createTimeEnd"));
		wrapper.lambda().orderByDesc(Comment::getId);
		return wrapper;
	}

	/**
	 * 数量统计
	 */
	public long countByParams(Map<String, Object> params) {
		return count(selectCommentWrapper(params));
	}

	/**
	 * 主题评论 前端
	 */
	@Transactional(rollbackFor = Exception.class)
    public Comment saveCommentTopic(CommentDTO commentDTO, Long userId) {
		Topic topic = topicService.getById(commentDTO.getTargetId());
		Assert.isNull(topic, MsgConstant.OBJECT_NULL);
		Assert.isNull(topic.getIsComment() == 1, "评论功能已关闭");
		topicService.updateById(Topic.builder().id(topic.getId()).commentNum(topic.getCommentNum() + 1).build());

		ConfigDTO.SocialDTO config = ConfigCache.getObject(ConfigKeys.SOCIAL, ConfigDTO.SocialDTO.class);
		if(config.getIsTopicComment() == 0){
			throw new ServiceException("评论功能已关闭");
		}

		Comment comment = new Comment();
		comment.setTargetId(topic.getId());
		comment.setTargetType(1);
		comment.setTargetTitle(topic.getTitle());
		comment.setParentId(0L);
		comment.setFromUserId(userId);
		comment.setToUserId(0L);
		comment.setContent(commentDTO.getContent());
		comment.setExtend(commentDTO.getExtend());
		comment.setCity(commentDTO.getCity());
		comment.setIsShow(1);
		comment.setStatus(config.getIsTopicCommentAudit() == 1 ? 0 : 1);
		comment.setCreateTime(new Date());
		save(comment);

//		eventPublisher.publishEvent(new NoticeEvent(2, userId, comment.getId(), NoticeEntityTypeEnum.COMMENT.getKey()));
		return comment;
    }

	/**
	 * 回复评论 前端
	 */
	@Transactional(rollbackFor = Exception.class)
	public Comment saveCommentReply(CommentDTO commentDTO, Long userId) {
		Comment data = getById(commentDTO.getTargetId());
		Assert.isNull(data, MsgConstant.OBJECT_NULL);

		ConfigDTO.SocialDTO config = ConfigCache.getObject(ConfigKeys.SOCIAL, ConfigDTO.SocialDTO.class);
		if(config.getIsTopicComment() == 0){
			throw new ServiceException("评论功能已关闭");
		}

		Comment comment = new Comment();
		comment.setTargetId(data.getTargetId());
		comment.setTargetType(2);
		comment.setTargetTitle(data.getContent());
		comment.setParentId(data.getParentId() == 0 ? data.getId() : data.getParentId());
		comment.setFromUserId(userId);
		comment.setToUserId(data.getFromUserId());
		comment.setContent(commentDTO.getContent());
		comment.setExtend(commentDTO.getExtend());
		comment.setCity(commentDTO.getCity());
		comment.setIsShow(1);
		comment.setStatus(config.getIsTopicCommentAudit() == 1 ? 0 : 1);
		comment.setCreateTime(new Date());
		save(comment);

//		eventPublisher.publishEvent(new NoticeEvent(2, userId, comment.getId(), NoticeEntityTypeEnum.COMMENT.getKey()));
		return comment;
	}

}
